package com.jiangyg.mall.db.hibernate.type;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;

/**
 * Descriptor for {@link Character} handling.
 *
 * @author Steve Ebersole
 */
public class CharacterTypeDescriptor extends AbstractTypeDescriptor<Character> {

	private static final long serialVersionUID = -6931199727435597186L;

	public static final CharacterTypeDescriptor INSTANCE = new CharacterTypeDescriptor();

	public CharacterTypeDescriptor() {
		super(Character.class);
	}

	public String toString(Character value) {
		return value.toString();
	}

	public Character fromString(String string) {
		if (string.length() != 1) {
			throw new HibernateException("multiple or zero characters found parsing string");
		}
		return string.charAt(0);
	}

	@SuppressWarnings({ "unchecked" })
	public <X> X unwrap(Character value, Class<X> type, WrapperOptions options) {
		if (value == null) {
			return null;
		}
		if (Character.class.isAssignableFrom(type)) {
			return (X) value;
		}
		if (String.class.isAssignableFrom(type)) {
			return (X) value.toString();
		}
		if (Number.class.isAssignableFrom(type)) {
			return (X) Short.valueOf((short) value.charValue());
		}
		throw unknownUnwrap(type);
	}

	public <X> Character wrap(X value, WrapperOptions options) {
		// 追加value为空字符串也返回逻辑 by jiangyg
		if (value == null || StringUtils.isBlank(value.toString())) {
			return null;
		}
		if (value instanceof Character) {
			return (Character) value;
		}
		if (value instanceof String) {
			final String str = (String) value;
			return str.charAt(0);
		}
		if (value instanceof Number) {
			final Number nbr = (Number) value;
			return (char) nbr.shortValue();
		}
		throw unknownWrap(value.getClass());
	}
}
